# 增强的系统管理数据模型
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import json


class SystemHealthCheck(models.Model):
    """系统健康检查记录模型"""
    STATUS_CHOICES = [
        ('healthy', '健康'),
        ('warning', '警告'),
        ('unhealthy', '不健康'),
        ('unknown', '未知'),
    ]
    
    # 检查结果
    overall_status = models.CharField(max_length=20, choices=STATUS_CHOICES, verbose_name="整体状态")
    results = models.JSONField(default=dict, verbose_name="检查结果")
    
    # 执行信息
    performed_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="执行人")
    performed_at = models.DateTimeField(auto_now_add=True, verbose_name="执行时间")
    duration = models.DurationField(null=True, blank=True, verbose_name="检查耗时")
    
    class Meta:
        verbose_name = "系统健康检查"
        verbose_name_plural = "系统健康检查"
        ordering = ['-performed_at']
    
    def __str__(self):
        return f"健康检查 - {self.performed_at.strftime('%Y-%m-%d %H:%M')} - {self.get_overall_status_display()}"


class SystemPerformanceMetric(models.Model):
    """系统性能指标模型"""
    METRIC_TYPE_CHOICES = [
        ('cpu_usage', 'CPU使用率'),
        ('memory_usage', '内存使用率'),
        ('disk_usage', '磁盘使用率'),
        ('network_io', '网络IO'),
        ('disk_io', '磁盘IO'),
        ('response_time', '响应时间'),
        ('throughput', '吞吐量'),
        ('error_rate', '错误率'),
        ('active_users', '活跃用户数'),
        ('database_connections', '数据库连接数'),
    ]
    
    metric_type = models.CharField(max_length=30, choices=METRIC_TYPE_CHOICES, verbose_name="指标类型")
    value = models.FloatField(verbose_name="指标值")
    unit = models.CharField(max_length=20, blank=True, verbose_name="单位")
    
    # 时间信息
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="记录时间")
    
    # 额外信息
    metadata = models.JSONField(default=dict, blank=True, verbose_name="元数据")
    
    class Meta:
        verbose_name = "系统性能指标"
        verbose_name_plural = "系统性能指标"
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['metric_type', '-timestamp']),
        ]
    
    def __str__(self):
        return f"{self.get_metric_type_display()} - {self.value}{self.unit} - {self.timestamp.strftime('%H:%M')}"


class SystemMaintenanceTask(models.Model):
    """系统维护任务模型"""
    TASK_TYPE_CHOICES = [
        ('backup', '数据备份'),
        ('cleanup', '数据清理'),
        ('optimize', '系统优化'),
        ('update', '系统更新'),
        ('security_scan', '安全扫描'),
        ('health_check', '健康检查'),
        ('custom', '自定义任务'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待执行'),
        ('running', '执行中'),
        ('completed', '已完成'),
        ('failed', '失败'),
        ('cancelled', '已取消'),
    ]
    
    PRIORITY_CHOICES = [
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('urgent', '紧急'),
    ]
    
    name = models.CharField(max_length=200, verbose_name="任务名称")
    description = models.TextField(blank=True, verbose_name="任务描述")
    task_type = models.CharField(max_length=20, choices=TASK_TYPE_CHOICES, verbose_name="任务类型")
    
    # 任务配置
    config = models.JSONField(default=dict, verbose_name="任务配置")
    
    # 执行信息
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name="状态")
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='medium', verbose_name="优先级")
    
    # 执行结果
    result = models.JSONField(null=True, blank=True, verbose_name="执行结果")
    error_message = models.TextField(blank=True, verbose_name="错误信息")
    
    # 时间信息
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="创建人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    scheduled_at = models.DateTimeField(null=True, blank=True, verbose_name="计划执行时间")
    started_at = models.DateTimeField(null=True, blank=True, verbose_name="开始时间")
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name="完成时间")
    
    class Meta:
        verbose_name = "系统维护任务"
        verbose_name_plural = "系统维护任务"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.name} - {self.get_status_display()}"
    
    @property
    def duration(self):
        """计算任务执行时长"""
        if self.started_at and self.completed_at:
            return self.completed_at - self.started_at
        return None


class SystemConfiguration(models.Model):
    """系统配置模型"""
    CONFIG_TYPE_CHOICES = [
        ('system', '系统配置'),
        ('security', '安全配置'),
        ('performance', '性能配置'),
        ('notification', '通知配置'),
        ('integration', '集成配置'),
        ('ui', '界面配置'),
    ]
    
    name = models.CharField(max_length=100, unique=True, verbose_name="配置名称")
    display_name = models.CharField(max_length=200, verbose_name="显示名称")
    description = models.TextField(blank=True, verbose_name="配置描述")
    config_type = models.CharField(max_length=20, choices=CONFIG_TYPE_CHOICES, verbose_name="配置类型")
    
    # 配置值
    value = models.TextField(verbose_name="配置值")
    default_value = models.TextField(blank=True, verbose_name="默认值")
    
    # 验证规则
    validation_rules = models.JSONField(default=dict, blank=True, verbose_name="验证规则")
    
    # 状态
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    is_readonly = models.BooleanField(default=False, verbose_name="是否只读")
    requires_restart = models.BooleanField(default=False, verbose_name="是否需要重启")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="更新人")
    
    class Meta:
        verbose_name = "系统配置"
        verbose_name_plural = "系统配置"
        ordering = ['config_type', 'name']
    
    def __str__(self):
        return self.display_name


class SystemAlert(models.Model):
    """系统预警模型"""
    ALERT_TYPE_CHOICES = [
        ('performance', '性能预警'),
        ('security', '安全预警'),
        ('error', '错误预警'),
        ('resource', '资源预警'),
        ('maintenance', '维护预警'),
        ('custom', '自定义预警'),
    ]
    
    SEVERITY_CHOICES = [
        ('info', '信息'),
        ('warning', '警告'),
        ('error', '错误'),
        ('critical', '严重'),
    ]
    
    STATUS_CHOICES = [
        ('active', '激活'),
        ('acknowledged', '已确认'),
        ('resolved', '已解决'),
        ('suppressed', '已抑制'),
    ]
    
    title = models.CharField(max_length=200, verbose_name="预警标题")
    message = models.TextField(verbose_name="预警消息")
    alert_type = models.CharField(max_length=20, choices=ALERT_TYPE_CHOICES, verbose_name="预警类型")
    severity = models.CharField(max_length=10, choices=SEVERITY_CHOICES, verbose_name="严重程度")
    
    # 预警数据
    alert_data = models.JSONField(default=dict, blank=True, verbose_name="预警数据")
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name="状态")
    
    # 处理信息
    acknowledged_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='acknowledged_system_alerts', verbose_name="确认人")
    acknowledged_at = models.DateTimeField(null=True, blank=True, verbose_name="确认时间")
    resolved_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='resolved_system_alerts', verbose_name="解决人")
    resolved_at = models.DateTimeField(null=True, blank=True, verbose_name="解决时间")
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "系统预警"
        verbose_name_plural = "系统预警"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.title} - {self.get_severity_display()}"


class SystemResource(models.Model):
    """系统资源监控模型"""
    RESOURCE_TYPE_CHOICES = [
        ('cpu', 'CPU'),
        ('memory', '内存'),
        ('disk', '磁盘'),
        ('network', '网络'),
        ('database', '数据库'),
        ('cache', '缓存'),
        ('queue', '队列'),
    ]
    
    resource_type = models.CharField(max_length=20, choices=RESOURCE_TYPE_CHOICES, verbose_name="资源类型")
    resource_name = models.CharField(max_length=100, verbose_name="资源名称")
    
    # 使用情况
    used = models.FloatField(verbose_name="已使用")
    total = models.FloatField(verbose_name="总量")
    usage_percent = models.FloatField(verbose_name="使用率")
    
    # 阈值
    warning_threshold = models.FloatField(default=80.0, verbose_name="警告阈值")
    critical_threshold = models.FloatField(default=90.0, verbose_name="严重阈值")
    
    # 状态
    status = models.CharField(max_length=20, default='normal', verbose_name="状态")
    
    # 时间信息
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="记录时间")
    
    # 额外信息
    metadata = models.JSONField(default=dict, blank=True, verbose_name="元数据")
    
    class Meta:
        verbose_name = "系统资源监控"
        verbose_name_plural = "系统资源监控"
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['resource_type', '-timestamp']),
        ]
    
    def __str__(self):
        return f"{self.get_resource_type_display()} - {self.resource_name} - {self.usage_percent}%"


class SystemIntegration(models.Model):
    """系统集成配置模型"""
    INTEGRATION_TYPE_CHOICES = [
        ('api', 'API集成'),
        ('database', '数据库集成'),
        ('file', '文件集成'),
        ('message_queue', '消息队列'),
        ('webhook', 'Webhook'),
        ('email', '邮件服务'),
        ('sms', '短信服务'),
        ('ldap', 'LDAP认证'),
        ('oauth', 'OAuth认证'),
        ('custom', '自定义集成'),
    ]
    
    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '未激活'),
        ('error', '错误'),
        ('testing', '测试中'),
    ]
    
    name = models.CharField(max_length=100, unique=True, verbose_name="集成名称")
    display_name = models.CharField(max_length=200, verbose_name="显示名称")
    description = models.TextField(blank=True, verbose_name="集成描述")
    integration_type = models.CharField(max_length=20, choices=INTEGRATION_TYPE_CHOICES, verbose_name="集成类型")
    
    # 配置信息
    config = models.JSONField(default=dict, verbose_name="配置信息")
    credentials = models.JSONField(default=dict, verbose_name="认证信息")
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='inactive', verbose_name="状态")
    is_enabled = models.BooleanField(default=False, verbose_name="是否启用")
    
    # 统计信息
    success_count = models.PositiveIntegerField(default=0, verbose_name="成功次数")
    error_count = models.PositiveIntegerField(default=0, verbose_name="错误次数")
    last_success_at = models.DateTimeField(null=True, blank=True, verbose_name="最后成功时间")
    last_error_at = models.DateTimeField(null=True, blank=True, verbose_name="最后错误时间")
    last_error_message = models.TextField(blank=True, verbose_name="最后错误信息")
    
    # 时间信息
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="创建人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "系统集成"
        verbose_name_plural = "系统集成"
        ordering = ['name']
    
    def __str__(self):
        return self.display_name


class SystemAuditLog(models.Model):
    """系统审计日志模型"""
    ACTION_TYPE_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('login', '登录'),
        ('logout', '登出'),
        ('access', '访问'),
        ('export', '导出'),
        ('import', '导入'),
        ('config_change', '配置变更'),
        ('permission_change', '权限变更'),
    ]
    
    RESULT_CHOICES = [
        ('success', '成功'),
        ('failure', '失败'),
        ('partial', '部分成功'),
    ]
    
    # 操作信息
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="操作用户")
    action_type = models.CharField(max_length=20, choices=ACTION_TYPE_CHOICES, verbose_name="操作类型")
    action_description = models.CharField(max_length=500, verbose_name="操作描述")
    
    # 对象信息
    object_type = models.CharField(max_length=50, blank=True, verbose_name="对象类型")
    object_id = models.CharField(max_length=50, blank=True, verbose_name="对象ID")
    object_name = models.CharField(max_length=200, blank=True, verbose_name="对象名称")
    
    # 操作结果
    result = models.CharField(max_length=10, choices=RESULT_CHOICES, verbose_name="操作结果")
    
    # 详细信息
    details = models.JSONField(default=dict, blank=True, verbose_name="详细信息")
    
    # 环境信息
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name="IP地址")
    user_agent = models.TextField(blank=True, verbose_name="用户代理")
    session_id = models.CharField(max_length=100, blank=True, verbose_name="会话ID")
    
    # 时间信息
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="操作时间")
    
    class Meta:
        verbose_name = "系统审计日志"
        verbose_name_plural = "系统审计日志"
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['user', '-timestamp']),
            models.Index(fields=['action_type', '-timestamp']),
            models.Index(fields=['object_type', 'object_id']),
        ]
    
    def __str__(self):
        return f"{self.user} - {self.get_action_type_display()} - {self.timestamp.strftime('%Y-%m-%d %H:%M')}"


class SystemBackupSchedule(models.Model):
    """系统备份计划模型"""
    BACKUP_TYPE_CHOICES = [
        ('full', '完整备份'),
        ('incremental', '增量备份'),
        ('differential', '差异备份'),
    ]
    
    FREQUENCY_CHOICES = [
        ('daily', '每日'),
        ('weekly', '每周'),
        ('monthly', '每月'),
    ]
    
    STATUS_CHOICES = [
        ('active', '激活'),
        ('paused', '暂停'),
        ('disabled', '禁用'),
    ]
    
    name = models.CharField(max_length=200, verbose_name="备份计划名称")
    description = models.TextField(blank=True, verbose_name="描述")
    backup_type = models.CharField(max_length=20, choices=BACKUP_TYPE_CHOICES, verbose_name="备份类型")
    
    # 计划配置
    frequency = models.CharField(max_length=20, choices=FREQUENCY_CHOICES, verbose_name="备份频率")
    execute_time = models.TimeField(verbose_name="执行时间")
    execute_day = models.PositiveIntegerField(null=True, blank=True, verbose_name="执行日期")
    
    # 备份配置
    backup_path = models.CharField(max_length=500, verbose_name="备份路径")
    retention_days = models.PositiveIntegerField(default=30, verbose_name="保留天数")
    compress = models.BooleanField(default=True, verbose_name="是否压缩")
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name="状态")
    
    # 统计信息
    last_backup_at = models.DateTimeField(null=True, blank=True, verbose_name="最后备份时间")
    next_backup_at = models.DateTimeField(null=True, blank=True, verbose_name="下次备份时间")
    backup_count = models.PositiveIntegerField(default=0, verbose_name="备份次数")
    
    # 时间信息
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="创建人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "系统备份计划"
        verbose_name_plural = "系统备份计划"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.name} - {self.get_frequency_display()}"